module client.MsgServerClient;

import hunt.logging;
import hunt.util.Serialize;
import std.conv : to;
import msgtrans;
import std.algorithm.mutation : SwapStrategy;
import std.algorithm.sorting;

static struct MsgServerNode {
    uint id;
    TransportContext client;
}


class MsgServerClient
{
    private __gshared MsgServerClient _instance;

    private MsgServerNode[] _forwardClientMap;

    private uint _size = 0;

    static public MsgServerClient getInstance()
    {
        if (_instance is null)
        {
            _instance = new MsgServerClient();
        }
        return _instance;
    }

    public void addForwardClient(uint id , TransportContext client)
    {
      //TODO if exist;
       synchronized(this)
       {
         foreach(MsgServerNode n ; _forwardClientMap)
         {
            if(n.id == id)
            {
                n.client = client;
                return;
            }
         }
         _forwardClientMap ~= MsgServerNode(id,client);
         multiSort!("a.id < b.id", SwapStrategy.unstable)(_forwardClientMap);
         _size += 1;
       }
    }


    public uint getSize()
    {
      return _size;
    }

    public TransportSession getForwardClient(int id)
    {
       logInfo("hash:%d",id % _size);
       return _forwardClientMap[id % _size].client.session();
    }
}
